package com.hns.can.master.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hns.can.master.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysCodeDscEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.aop.orgTree.LeftOrgAnnotation;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.domain.ReturnResult;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.vo.ParkingLotCarDetailVo;
import com.hns.can.master.vo.ParkingLotCarTotalVo;
import com.hns.can.master.vo.ParkingLotForCarParamVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;

/**
 * 停车场Service
 * @author:zhangzq
 * @email:
 * @version Revision 2.0.0
 */
@Service
public class SysParkingService extends CommonService {
	
    @Autowired
    private FillCodeDscValue codeDscValue;

    /**
     * 填充机构名称
     * @param list
     * @throws Exception
     */
    private void fillOrganName(List list) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo = new FillParamsVo("organId", map);
        codeDscValue.fillInfoValue(list,new String[]{GlobalConst.CACHE_KEY_BASE_ORGAN},vo);
    }

    /**
     * 填充车辆信息
     * @param list
     * @throws Exception
     */
    private void fillCarInfo(List list) throws Exception {
        Map<String,String> map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("lineId", map);
        map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map);
        codeDscValue.fillInfoValue(list,new String[]{GlobalConst.CACHE_KEY_BASE_LINE_INFO,GlobalConst.CACHE_KEY_BASE_CAR_INFO},vo1,vo2);
    }

    /**
     * 根据组织补充停车场省份与城市信息
     * @param organId
     * @param entity
     * @throws Exception
     */
    private void addAreaInfoByOrgan(String organId,BaseParkingLotInfoEntity entity){
        BaseOrganEntity baseOrganEntity = commonEntityDao.find(organId,BaseOrganEntity.class);
        if(PubUtil.isEmpty(baseOrganEntity.getProvinceId())){
            throw new BusinessException(MsgType.WARN.getFlag(), "该机构"+baseOrganEntity.getOrganName()+"未维护省份。");
        }
        if(PubUtil.isEmpty(baseOrganEntity.getCityId())){
            throw new BusinessException(MsgType.WARN.getFlag(), "该机构"+baseOrganEntity.getOrganName()+"未维护城市。");
        }
        entity.setProvinceId(baseOrganEntity.getProvinceId());
        entity.setCityId(baseOrganEntity.getCityId());
    }

    /**
     * 添加停车场信息
     * @param entity
     * @param user
     * @return
     * @throws Exception
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
    public ReturnResult addParkingInfo(BaseParkingLotInfoEntity entity, SysUserEntity user) throws Exception{
        addAreaInfoByOrgan(entity.getOrganId(),entity);
        String jpql="select o from SysCodeDscEntity o where o.codeValue= ?1 ";        
        SysCodeDscEntity sysCodeDscEntity=commonEntityDao.findOneByJpql(jpql, new Object[]{entity.getCityId()});
        if(sysCodeDscEntity==null||PubUtil.isEmpty(sysCodeDscEntity.getRemark())){
        	throw new BusinessException(MsgType.WARN.getFlag(), "该城市未维护区号。");
        }
        String remark = sysCodeDscEntity.getRemark();
        if(remark.length()<4) {
        	remark ="0"+remark;
        }
        Map map = new HashMap();
        map.put("cityId", entity.getCityId());
        String parkingCd = (String) sqlMapDao.selectOne("baseParkingInfo.getMaxParkingCd", map);
        //创建停车场编号
		if(PubUtil.isEmpty(parkingCd)){			
			parkingCd=new String(remark+"0001");
		}
		else{
			parkingCd=parkingCd.substring(4);
			Integer newCd=new Integer(parkingCd);
			newCd+=1;
			String str = String.valueOf(newCd);
			str="0000"+str;
			parkingCd=new String(remark+str.substring(str.length()-4));
		}
        String parkingId = UtilString.getUUID();
        entity.setParkingLotCd(parkingCd);
        entity.setParkingId(parkingId);
        entity.setCorpId(user.getCorpId());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        commonEntityDao.save(entity);
        List<BaseParkingGpsInfoEntity> parkingGpsList=entity.getGpsList();
        if(PubUtil.isNotEmpty(parkingGpsList)){
            for(int i=0;i<parkingGpsList.size();i++){
                BaseParkingGpsInfoEntity item=parkingGpsList.get(i);
                item.setGpsId(UtilString.getUUID());
                item.setParkingLotId(parkingId);
                item.setUpdateTime(new Date());
                item.setUpdateUser(user.getAcctName());
                commonEntityDao.save(item);
            }
        }
        return new ReturnResult("新增停车场成功,停车场编号为："+parkingCd,null);
	}

    /**
     * 更新停车场信息
     * @param entity
     * @param user
     * @throws Exception
     */
	@SuppressWarnings("unchecked")
	@Transactional
    public void updParkingInfo(BaseParkingLotInfoEntity entity,SysUserEntity user) throws Exception{
		String parkingId = entity.getParkingId();
		BaseParkingLotInfoEntity origEntity = commonEntityDao.find(parkingId,BaseParkingLotInfoEntity.class);
		if(!origEntity.getOrganId().equals(entity.getOrganId())){
            addAreaInfoByOrgan(entity.getOrganId(),entity);
        }
		entity.setCorpId(user.getCorpId());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        commonEntityDao.update(entity);
        //删除原来停车场经纬度集
        Map map = new HashMap();
        map.put("parkingLotId", parkingId);
        commonEntityDao.deleteByParamsIgnoreNullValue(BaseParkingGpsInfoEntity.class, map);
      //添加新停车场经纬度集
        List<BaseParkingGpsInfoEntity> parkingGpsList=entity.getGpsList();
        if(PubUtil.isNotEmpty(parkingGpsList)){
            for(int i=0;i<parkingGpsList.size();i++){
                BaseParkingGpsInfoEntity item=parkingGpsList.get(i);
                item.setGpsId(UtilString.getUUID());
                item.setParkingLotId(parkingId);
                item.setUpdateTime(new Date());
                item.setUpdateUser(user.getAcctName());
                commonEntityDao.save(item);
            }
        }
	}
	
	/**
	 * 根据ID删除停车场信息
	 * @param parkingId
	 * @author:zhangzq
	 * @email:
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public void delParkingInfo(String parkingId) throws Exception{
		commonEntityDao.delete(BaseParkingLotInfoEntity.class, new String[]{parkingId});
        //删除停车场经纬度集
        Map map = new HashMap();
        map.put("parkingLotId", parkingId);
        commonEntityDao.deleteByParamsIgnoreNullValue(BaseParkingGpsInfoEntity.class, map);
	}
	
	/**
	 * 根据ID获取停车场基本信息
	 * @param parkingId
	 * @return
	 * @author:zhangzq
	 * @email:
	 */
	public BaseParkingLotInfoEntity getBaseParkingLotInfoById(String parkingId){
		return commonEntityDao.find(parkingId,BaseParkingLotInfoEntity.class);
	}
	
	/**
	 * 根据ID获取停车场经纬度集
	 * @param parkingId
	 * @return
	 * @author:zhangzq
	 * @email:
	 */
	@SuppressWarnings("unchecked")
	public List<BaseParkingGpsInfoEntity> getBaseParkingGpsListById(String parkingId){
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap.put("parkingId", parkingId);
		List<BaseParkingGpsInfoEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("baseParkingInfo.getBaseParkingGpsList",paramMap),BaseParkingGpsInfoEntity.class);
		return list;
	}
	
	/**
	 * 分页查询停车场基本信息
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
	@Transactional
    public Pagination searchParkingInfoPage(Map<String, Object> paramMap)  throws Exception{
		Pagination page = this.myBatisPage("baseParkingInfo.getParkingInfoCnt","baseParkingInfo.getParkingInfoList", paramMap,BaseParkingLotInfoEntity.class);
		List list = page.getData();
        fillOrganName(list);
		page.setData(list);
		return page;
	}

	/**
	 * 导出停车场信息
	 * @param organId
	 * @param parkingLotName
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
    @SuppressWarnings("unchecked")
	public List<BaseParkingLotInfoEntity> exportParkingInfo(String organId,String parkingLotName)  throws Exception{
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	paramMap.put("organId", organId);
    	paramMap.put("parkingLotName", parkingLotName);
		List<BaseParkingLotInfoEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("baseParkingInfo.exportParkingInfo",paramMap),BaseParkingLotInfoEntity.class);
        fillOrganName(list);
		return list;
	}
	
	/**
	 * 根据用户OrgId获取停车场
	 * @param orgId
	 * @return
	 * @author:zhangzq
	 * @email:
	 */
	@SuppressWarnings("unchecked")
	public List<BaseParkingLotInfoEntity> getParkingInfoListByOrgId(String orgId){
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap.put("organId", orgId);
		List<BaseParkingLotInfoEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("baseParkingInfo.getParkingInfoListByOrgId",paramMap),BaseParkingLotInfoEntity.class);
		return list;
	}

    /**
     * 分页查询停车场进场车辆
     * @param paramVo
     * @param user
     * @return
     * @throws Exception
     */
	@SuppressWarnings("unchecked")
	@Transactional
	@LeftOrgAnnotation()
    public Pagination searchCarInoutParkingInfoPage(ParkingLotForCarParamVo paramVo,SysUserEntity user)throws Exception{
    	List<String> cdList=new ArrayList<String>();
    	if("All".equals(paramVo.getParkingLotCd())){    		
			String orgId=user.getOrganId();
			List<BaseParkingLotInfoEntity> parkingList=getParkingInfoListByOrgId(orgId);
            if(PubUtil.isNotEmpty(parkingList)){
                for (int i=0;i<parkingList.size();i++){
                    BaseParkingLotInfoEntity item = parkingList.get(i);
                    cdList.add(item.getParkingLotCd());
                }
            }
    	}
    	else{
    		cdList.add(paramVo.getParkingLotCd());
    	}
    	paramVo.setCdList(cdList);
		Pagination page = this.myBatisPage("baseParkingInfo.getCarInoutParkingInfoCnt","baseParkingInfo.getCarInoutParkingInfoList", paramVo,CommCarInoutParkingInfoEntity.class);
		List list = page.getData();
        fillCarInfo(list);
        page.setData(list);
		return page;
	}
	
	/**
	 * 导出停车场内车辆出入场信息
	 * @param paramVo
	 * @return
	 * @author:zhangzq
	 * @email:
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	@LeftOrgAnnotation()
	public List<CommCarInoutParkingInfoEntity> exportCarInoutParkingInfo(ParkingLotForCarParamVo paramVo,SysUserEntity user)throws Exception{
    	List<String> cdList=new ArrayList<String>();
    	if("All".equals(paramVo.getParkingLotCd())){    		
			String orgId=user.getOrganId();
			List<BaseParkingLotInfoEntity> parkingList=getParkingInfoListByOrgId(orgId);
            if(PubUtil.isNotEmpty(parkingList)){
                for (int i=0;i<parkingList.size();i++){
                    BaseParkingLotInfoEntity item = parkingList.get(i);
                    cdList.add(item.getParkingLotCd());
                }
            }
    	}
    	else{
    		cdList.add(paramVo.getParkingLotCd());
    	}
    	paramVo.setCdList(cdList);
		List list = PubUtil.convertListMapToObject(sqlMapDao.selectList("baseParkingInfo.exportCarInoutParkingInfo", paramVo),CommCarInoutParkingInfoEntity.class);
        fillCarInfo(list);
		return list;
	}
	
	/**
	 * 分页查询停车场内车辆汇总
	 * @param vo
	 * @param user
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
    @LeftOrgAnnotation()
    @Transactional
	public Pagination searchParkingLotCarTotalPage(ParkingLotForCarParamVo vo,SysUserEntity user)  throws Exception{
    	List<String> cdList=new ArrayList<String>();
    	if("All".equals(vo.getParkingLotCd())){    		
			String orgId=user.getOrganId();
			List<BaseParkingLotInfoEntity> parkingList=getParkingInfoListByOrgId(orgId);
            if(PubUtil.isNotEmpty(parkingList)){
                for (int i=0;i<parkingList.size();i++){
                    BaseParkingLotInfoEntity item = parkingList.get(i);
                    cdList.add(item.getParkingLotCd());
                }
            }
    	}
    	else{
    		cdList.add(vo.getParkingLotCd());
    	}
    	vo.setCdList(cdList);
    	Pagination page = this.myBatisPage("baseParkingInfo.getParkingLotCarTotalCnt","baseParkingInfo.getParkingLotCarTotalList", vo,ParkingLotCarTotalVo.class);
    	return page;
	}
    
	/**
	 * 分页查询停车场内车辆明细
	 * @param vo
	 * @param user
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
    @LeftOrgAnnotation()
    @Transactional
	public Pagination searchParkingLotCarDetailPage(ParkingLotForCarParamVo vo,SysUserEntity user)  throws Exception{
    	List<String> cdList=new ArrayList<String>();
    	if("All".equals(vo.getParkingLotCd())){    		
			String orgId=user.getOrganId();
			List<BaseParkingLotInfoEntity> parkingList=getParkingInfoListByOrgId(orgId);
            if(PubUtil.isNotEmpty(parkingList)){
                for (int i=0;i<parkingList.size();i++){
                    BaseParkingLotInfoEntity item = parkingList.get(i);
                    cdList.add(item.getParkingLotCd());
                }
            }
    	}
    	else{
    		cdList.add(vo.getParkingLotCd());
    	}
    	vo.setCdList(cdList);
    	Pagination page = this.myBatisPage("baseParkingInfo.getParkingLotCarDetailCnt","baseParkingInfo.getParkingLotCarDetailList", vo,ParkingLotCarDetailVo.class);
    	return page;
	}
	
}
